package listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @author Mark
 * @date 2020/5/26 22:24
 * @description online
 */
public class OnlineListener implements HttpSessionListener {


    /**
     * 創建
     *
     * @param se HttpSessionEvent
     */
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext servletContext = se.getSession().getServletContext();
        Integer onLineCount = (Integer) servletContext.getAttribute("onLineCount");
        if (onLineCount == null) {
            onLineCount = new Integer(1);
        } else {
            int i = onLineCount.intValue();
            onLineCount = new Integer(i + 1);
        }

        servletContext.setAttribute("onLineCount", onLineCount);
    }

    /**
     * 銷毀
     *
     * @param se HttpSessionEvent
     */
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext servletContext = se.getSession().getServletContext();
        Integer onLineCount = (Integer) servletContext.getAttribute("onLineCount");
        if (onLineCount == null) {
            onLineCount = new Integer(0);
        } else {
            int i = onLineCount.intValue();
            onLineCount = new Integer(i - 1);
        }

        servletContext.setAttribute("onLineCount", onLineCount);
    }
}
